<template>
  <div class="chat-app">
    <div class="chat-header">
      <h1>AI编程小助手</h1>
      <div class="room-info">
        <span>聊天室ID:</span> <span id="room-id">{{ roomId }}</span>
      </div>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="message in messages" :key="message.id" :class="['message', message.sender === 'user' ? 'user-message' : 'ai-message']">
        <div class="avatar">
          <i :class="message.sender === 'user' ? 'fas fa-user' : 'fas fa-robot'"></i>
        </div>
        <div class="message-content">
          <div class="sender-name">{{ message.sender === 'user' ? '你' : 'AI助手' }}</div>
          <div class="message-text" v-html="formatMessage(message.text)"></div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <textarea
        v-model="inputMessage"
        placeholder="输入你的问题..."
        @keydown.enter.exact="sendMessage"
        @keydown.enter.shift="addNewline"
      ></textarea>
      <button @click="sendMessage" :disabled="!inputMessage.trim()">
        <i class="fas fa-paper-plane"></i> 发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';

// 生成随机聊天室ID
function generateRoomId() {
  return 'room_' + Math.random().toString(36).substring(2, 10);
}

// 格式化消息内容（支持简单的代码块）
function formatMessage(text) {
  // 将 ```code``` 格式化为代码块
  text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
  // 将换行符转换为<br>
  return text.replace(/\n/g, '<br>');
}

const roomId = ref(generateRoomId());
const messages = ref([]);
const inputMessage = ref('');
const messagesContainer = ref(null);
const isLoading = ref(false);
const eventSourceRef = ref(null);

// 添加系统消息
const addSystemMessage = (text) => {
  messages.value.push({
    id: Date.now(),
    sender: 'system',
    text: text
  });
  scrollToBottom();
};

// 滚动到消息底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 发送消息
const sendMessage = () => {
  const messageText = inputMessage.value.trim();
  if (!messageText || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    sender: 'user',
    text: messageText
  });

  inputMessage.value = '';
  scrollToBottom();
  isLoading.value = true;

  // 关闭之前的SSE连接
  if (eventSourceRef.value) {
    eventSourceRef.value.close();
    eventSourceRef.value = null;
  }

  // 添加AI正在输入的消息
  const aiMessageId = Date.now() + 1;
  messages.value.push({
    id: aiMessageId,
    sender: 'ai',
    text: '正在输入...',
    isStreaming: true
  });
  scrollToBottom();

  // 建立SSE连接
  const apiUrl = `/api/ai/chat?memoryId=${roomId.value}&userMessage=${encodeURIComponent(messageText)}`;
  eventSourceRef.value = new EventSource(apiUrl);

  // 处理SSE事件
  eventSourceRef.value.onmessage = (event) => {
    try {
      const data = event.data;
      // 查找AI消息并更新
      const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
      if (aiMessageIndex !== -1) {
        // 如果是首次收到数据，替换"正在输入..."
        if (messages.value[aiMessageIndex].text === '正在输入...') {
          messages.value[aiMessageIndex].text = data;
        } else {
          // 否则追加内容
          messages.value[aiMessageIndex].text += data;
        }
        scrollToBottom();
      }
    } catch (error) {
      console.error('处理SSE消息时出错:', error);
    }
  };

  eventSourceRef.value.onerror = (error) => {
    console.error('SSE连接错误:', error);
    const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
    if (aiMessageIndex !== -1) {
      messages.value[aiMessageIndex].text = '连接出错，请重试';
      messages.value[aiMessageIndex].isStreaming = false;
    }
    isLoading.value = false;
    eventSourceRef.value.close();
    eventSourceRef.value = null;
  };

  eventSourceRef.value.onopen = () => {
    console.log('SSE连接已建立');
  };

  eventSourceRef.value.onclose = () => {
    console.log('SSE连接已关闭');
    const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId);
    if (aiMessageIndex !== -1) {
      messages.value[aiMessageIndex].isStreaming = false;
    }
    isLoading.value = false;
  };
};

// 添加换行（Shift+Enter）
const addNewline = () => {
  inputMessage.value += '\n';
};

// 组件挂载时
onMounted(() => {
  addSystemMessage('欢迎使用AI编程小助手！请输入您的问题，我会尽力为您解答。');
  console.log(`当前聊天室ID: ${roomId.value}`);
});
</script>

<style scoped>
/* 这里只放组件特定的样式，全局样式放在src/style.css */
.chat-app {
  max-width: 1000px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  background-color: #4a6ea9;
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  margin: 0;
  font-size: 1.5rem;
}

.room-info {
  font-size: 0.9rem;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 5px 10px;
  border-radius: 15px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.message {
  margin-bottom: 15px;
  display: flex;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 10px;
  flex-shrink: 0;
}

.user-message .avatar {
  background-color: #4a6ea9;
  color: white;
}

.ai-message .avatar {
  background-color: #67c23a;
  color: white;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.user-message .message-content {
  background-color: #93c5fd;
}

.ai-message .message-content {
  background-color: white;
}

.sender-name {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 0.85rem;
}

.message-text {
  word-break: break-word;
  line-height: 1.5;
}

.message-text pre {
  background-color: #f1f1f1;
  padding: 10px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 10px 0;
}

.message-text code {
  font-family: 'Courier New', Courier, monospace;
}

.chat-input {
  display: flex;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
}

.chat-input textarea {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  resize: none;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s;
  min-height: 40px;
  max-height: 120px;
}

.chat-input textarea:focus {
  border-color: #4a6ea9;
}

.chat-input button {
  margin-left: 10px;
  padding: 0 20px;
  background-color: #4a6ea9;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
}

.chat-input button:hover {
  background-color: #3a5a89;
}

.chat-input button:disabled {
  background-color: #a0aec0;
  cursor: not-allowed;
}

.chat-input button i {
  margin-right: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-app {
    height: 100vh;
    width: 100%;
  }

  .message {
    max-width: 90%;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message {
  animation: fadeIn 0.3s ease-in-out;
}
</style>